<?php
session_start ();

include_once ('../config.php');
include_once ('rennclient/RennClient.php');

$rennClient = new RennClient ( RENREN_APP_KEY, RENREN_APP_SECRET );
$rennClient->setDebug ( DEBUG_MODE );

// 处理code -- 根据code来获得token
if (isset ( $_REQUEST ['code'] )) {
	$keys = array ();
	
	// 验证state，防止伪造请求跨站攻击
	/*$state = $_REQUEST ['state'];
	if (empty ( $state ) || $state !== $_SESSION ['renren_state']) {
		echo '非法请求！';
		exit ();
	}*/
	unset ( $_SESSION ['renren_state'] );
	
	// 获得code
	$keys ['code'] = $_REQUEST ['code'];
	$keys ['redirect_uri'] = RENREN_CALLBACK_URL;
	try {
		// 根据code来获得token
		$renren_token = $rennClient->getTokenFromTokenEndpoint ( 'code', $keys );
	} catch ( RennException $e ) {
		var_dump ( $e );
	}
}
echo '<br/>';
if ($renren_token) {
	//dump($renren_token);
	$renren_token_new = array();
	foreach ($renren_token as $key => $value) {
		$renren_token_new[$key] = $value;
	}
	//dump($renren_token_new);
	
	$MAC_TOKEN = $renren_token_new['accessToken'];
	$MAC_KEY = $renren_token_new['macKey'];
	$MAC_ALGORITHM = $renren_token_new['macAlgorithm'];
	$accessToken = new AccessToken ( TokenType::MAC, $MAC_TOKEN, null, $MAC_KEY, $MAC_ALGORITHM );
	$rennClient->authWithToken($accessToken);
	
	/*获取用户信息*/
	$user_service = $rennClient->getUserService ();
	$user = $user_service->getUserLogin ();
	//dump($user);
	$userId = $user['id'];
    $userName = $user['name'];
    $token = $renren_token_new['accessToken'].'_'.$renren_token_new['macKey'].'_'.$renren_token_new['macAlgorithm'];
	$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD); 
    mysql_select_db(DB_NAME,$con);
    mysql_query("SET NAMES utf8");
    if($userId){
        $sql="select * from cai_uid where sns='renren' and uid='".trim($userId)."'"; 
        $result=mysql_query($sql);
        $row = mysql_fetch_array($result, MYSQL_ASSOC);
        if (!mysql_num_rows($result)){
            $sql2="INSERT INTO `cai_uid` (`id`, `uid`, `token` , `name`,`sns`,`expires`) VALUES (NULL,'".trim($userId)."','".$token."','".$userName."','renren','0');";
            if(mysql_query($sql2)){
                echo "插入成功";
            }else{
                echo "插入成功";
            } 
        }else{
            $sql3="UPDATE `cai_uid` SET `token` =  '".$token."' ,`name` =  '".$userName."',`expires` =  '0' WHERE  uid='".$userName."' and sns= 'renren';";
            if(mysql_query($sql3)){
                echo "更新成功";
            }else{
                echo "更新失败";
            } 
        }
    }
echo '授权完成,<br/><a href="../shouquan.php">查看所有授权</a><br />';
} else {
	echo '授权失败。';
}
?>
